package br.com.megasena.infraestrutura;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import br.com.megasena.dominio.Sorteio;

public class SorteioRepository {
	private EntityManagerFactory emf = PersistenceContextSingleton.getInstance().getEntityManagerFactory();
	
	/**
	 * Adiciona Sorteio
	 */
	public void add(Object object){
		//Objem EntityManager
		EntityManager em = this.emf.createEntityManager();
		try {
			EntityTransaction et = em.getTransaction();
			try {
				et.begin();
				em.persist(object);
				et.commit();
			} finally {
				if(et.isActive()){
					et.rollback();
				}
			}
		} finally {
			em.close();
		}
	}
	
	/**
	 * Lista Sorteios Cadastrados
	 * @return sorteios
	 */
	public List<Sorteio> lista(){
		List<Sorteio> sorteios = null;
		EntityManager em = this.emf.createEntityManager();
		try {
			EntityTransaction et = em.getTransaction();
			try {
				et.begin();
				Query query = em.createQuery("SELECT s FROM Sorteio s ORDER BY s.concurso");
				sorteios = query.getResultList();
				et.commit();
			} finally {
				if(et.isActive()){
					et.rollback();
				}
			}
		} finally {
			em.close();
		}
		return sorteios;
	}
}
